# 忽视warning
import warnings
warnings.filterwarnings('ignore')
# 读入文件
import pandas as pd
file=open('iris_nan.csv',encoding='cp936')
iris=pd.read_csv(file)

# 打出前几行
# print(iris.head(67))
# print(iris.dtypes)
# 查看数据是否有缺失
# print(iris.isnull().sum())

# knn填充
# from fancyimpute import KNN
# fill_knn=KNN(k=2).fit_transform(iris)
# iris=pd.DataFrame(fill_knn)
# 使用平均值进行填充
iris=iris.fillna(iris.mean())
# print(iris.isnull().sum())

# 查看数据特征
import matplotlib.pyplot as plt
import seaborn as sns
from pylab import mpl
# 解决sns画图图中不能显示中文和符号的问题
sns.set(font='SimHei')
mpl.rcParams['axes.unicode_minus']=False

# # 小提琴图
# f, axes=plt.subplots(2,2,figsize=(7,7),sharex=True)
# sns.despine()
# sns.violinplot(x='花的品种',y='花萼长度',data=iris,split=True,ax=axes[0,0])
# axes[0,0].set_title('花的品种与花萼长度',fontsize=11)
# sns.violinplot(x='花的品种',y='花萼宽度',data=iris,ax=axes[0,1])
# axes[0,1].set_title('花的品种与花萼宽度',fontsize=11)
# sns.violinplot(x='花的品种',y='花瓣长度',data=iris,ax=axes[1,0])
# axes[1,0].set_title('花的品种与花瓣长度',fontsize=11)
# sns.violinplot(x='花的品种',y='花瓣宽度',data=iris,ax=axes[1,1])
# axes[1,1].set_title('花的品种与花瓣宽度',fontsize=11)
# plt.show()

# 热力图
# fig=plt.gcf()
# fig.set_size_inches(12,8)
# fig=sns.heatmap(iris.corr(),annot=True,cmap="RdBu_r",linewidths=1,linecolor='k',square=True,
#                 mask=False, vmin=-1,vmax=1,cbar_kws={"orientation": "vertical"},cbar=True)
# plt.show()

# 划分训练集和测试集
from sklearn.model_selection import train_test_split
train,test=train_test_split(iris,test_size=0.3)
train_X=train[['花萼长度','花萼宽度','花瓣长度','花瓣宽度']]
train_y=train.花的品种
test_X=test[['花萼长度','花萼宽度','花瓣长度','花瓣宽度']]
test_y=test.花的品种

# # 决策树
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
from sklearn import metrics
model_t=DecisionTreeClassifier()
model_t.fit(train_X,train_y)
prediction_t=model_t.predict(test_X)
iris.feature_names=['花萼长度','花萼宽度','花瓣长度','花瓣宽度']
iris.target_names=['0','1','2']

# 可视化决策树模型并打印出特征属性的重要性
tree.plot_tree(model_t,feature_names=iris.feature_names,
               class_names=iris.target_names,rounded=True,filled=True);
plt.show()
# plt.savefig('tree.png',bbox_inches='tight')
print(model_t.feature_importances_)
print('The accuracy of the Decision Tree is',metrics.accuracy_score(prediction_t,test_y))

# # KNN——K折邻近算法,k值取3
# from sklearn.neighbors import KNeighborsClassifier
# model_k=KNeighborsClassifier(n_neighbors=3)
# model_k.fit(train_X,train_y)
# prediction_k=model_k.predict(test_X)
# print('The accuracy of the KNN is',metrics.accuracy_score(prediction_k,test_y))

# # 朴素贝叶斯
# from sklearn.naive_bayes import GaussianNB
# model_b=GaussianNB()
# model_b.fit(train_X,train_y)
# prediction_b=model_b.predict(test_X)
# print('The accuracy of the GaussianNB is',metrics.accuracy_score(prediction_b,test_y))